// pages/sub/subs/subs.js
var app = getApp()
var handler = require('../../../utils/dataHander')
const db = wx.cloud.database()
const tiku = db.collection("shuati")
import dataUtils  from '../../../utils/getDataUtil'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topSubject: "",
    learnType: ["顺序练习", "随机练习", "收藏练习", "开始考试", "错题练习", "重新练习", "考卷回顾"],
    titleImage: "",
    spinflag: true,
    searchItem: {
      title: ""
    },
    search: "cloud://jiwu-5glbnwui4460186f.6a69-jiwu-5glbnwui4460186f-1312639486/search.png",
    touch: ""
  },

  // 未来会在这里做模糊查询的功能，现在还做不了
  setSearchItem: function (e) {
    this.setData({
      [`${e.currentTarget.dataset.gater}`]: e.detail.value
    })
  },

  // 进行模糊查询的方法
  search: async function (e) {
    this.setData({
      spinflag: false
    })
    let res = await dataUtils.searchTitle(this.data.searchItem.title,app.globalData.selectLib)
    if (res.length==0) {
      wx.showToast({
        icon:"error",
        title: '没有找到!',
      })
      this.setSpin()
      return
    }
    //跳转到顺序练习页面
    app.globalData.ButtomFlag = false
    app.globalData.learnType = "随机练习"
    app.globalData.practiceFlag = false
    wx.setStorageSync('subject', res)
    this.setSpin()
    wx.navigateTo({
      url: '../../sub/learns/learn',
    })
  },

  registerUser: async function (item) {
    //注册userRecord,只有顺序练习才需要注册userRecord
    let res = await wx.cloud.database().collection("userRecord").where({
      account: item.account,
      selectLib: app.globalData.selectLib
    }).get()
    if (res.data.length < 1) { //说明没查到数据，说明用户没有收藏过题目，进行添加
      let res1 = await wx.cloud.database().collection("userRecord").add({
        data: {
          account: item.account,
          selectLib: app.globalData.selectLib,
        }
      })
      return res1.errMsg
    }
    return res.errMsg
  },


  registed: async function (item, lib, info) {
    /**
     * 点击gotolearn，注册
     * 1.userRecord
     * 2.将其放入缓存中
     * 3.以后直接查询缓存，如果缓存中没有相关信息，再去数据库查找，减少数据库查找次数
     */
    let info1 = await this.registerUser(item)
    if (info1 == "collection.get:ok" || info1 == "collection.add:ok") {
      //将用户注册信息放到缓存中
      if (info) { //如果缓存里原来有数据，使用push方法
        info.push(lib)
      } else {
        info = new Array()
        info.push(lib)
      }
      //对info去重
      info = await handler.unique(info)
      wx.setStorage({
        key: item.account,
        data: info
      })
    }
    return info1
  },

  setSpin: async function (params) {
    this.setData({
      spinflag: true
    })
  },

  gotoLearn: function (e) {
    //进行数据库注册的异步函数    
    let item = wx.getStorageSync('user')
    let info = wx.getStorageSync(item.account)
    let lib = app.globalData.selectLib.toString()
    let selectLib = app.globalData.selectLib
    //如果缓存中没有信息， 重新去数据库确认有无注册过一次，避免每次都去数据库查询
    if (!info || (info && !info.includes(lib))) {
      this.registed(item, lib, info).then(res => {
        console.log(res)
      })
    }
    app.globalData.practiceFlag = false
    var that = this
    that.setData({
      spinflag: false
    })
    var flag = e.currentTarget.id
    app.globalData.learnType = flag
    if (flag !== "开始考试" && flag !== "考卷回顾") {
      app.globalData.ButtomFlag = false
      if (flag === "随机练习") {
        // 如果是随机练习，这里要将题库顺序打乱
        handler.randomPromise().then(() => {
          that.setSpin()
          wx.navigateTo({
            url: '../../sub/learns/learn',
          })
        })
      } else if (flag === "顺序练习") {
        //否则不将题库打乱，直接进入练习页面
        //在这里在数据库中查询到相应题库的题目
        tiku.where({
          name: selectLib
        }).get().then(res => {
          //拿到对应科目下的所有题
          wx.setStorageSync('subject', res.data[0].title)
          that.setSpin()
          wx.navigateTo({
            url: '../../sub/learns/learn',
          })
          return
        })
      } else if (flag === "错题练习") {
        wx.cloud.callFunction({
          name: 'test',
          data: {
            account: item.account,
            selectLib: selectLib
          }
        }).then(res => {
          console.log("进入云函数进行计算", res.errMsg)
          if (res.result == "没有错题") {
            wx.showToast({
              icon: "success",
              title: res.result,
            })
            that.setSpin()
            return
          } else {
            //将题目设置到缓存中
            wx.setStorageSync('subject', res.result)
            that.setSpin()
            wx.navigateTo({
              url: '../../sub/learns/learn',
            })
          }
        })
      } else if (flag === "重新练习") {
        wx.showModal({
          confirmColor: "#FF0000",
          title: '警告',
          content: '重新练习会清空您的学习记录！',
          complete: (res) => {
            that.setSpin()
            if (res.cancel) {
              return
            }
            if (res.confirm) {
              this.clearRecord(item, selectLib)
            }
          }
        })
      } else {
        //进入收藏练习页面
        // 从数据库中查到收藏的题库
        wx.cloud.callFunction({
          name: 'getFav',
          data: {
            account: item.account,
            selectLib: selectLib
          }
        }).then(res => {
          console.log("进入云函数进行计算", res.errMsg)
          if (res.result.length < 1) {
            wx.showToast({
              icon: "error",
              title: "没有收藏过",
            })
            that.setSpin()
            return
          } else {
            //将题目设置到缓存中
            wx.setStorageSync('subject', res.result)
            that.setSpin()
            wx.navigateTo({
              url: '../../sub/learns/learn',
            })
          }
        })
      }
    } else if (flag === "考卷回顾") {
      that.setSpin()
      wx.navigateTo({
        url: '../records/records',
      })
    } else {
      app.globalData.ButtomFlag = true
      handler.randomTestPromise().then(res => {
        that.setSpin()
        wx.navigateTo({
          url: '../../sub/tests/test',
        })
      })
    }
  },

  clearRecord: async function (item, selectLib) {
    var selectLib = app.globalData.selectLib
    var item = wx.getStorageSync('user')
    let resUser = await wx.cloud.database().collection("userRecord").where({
      account: item.account,
      selectLib: app.globalData.selectLib
    }).get()
    let answersRecord = resUser.data[0].answers
    if (typeof (answersRecord) == 'undefined') {
      wx.showToast({
        icon: "error",
        title: '您还没有练习过',
      })
      return
    } else {
      //更新，将题库清空
      //用answers将数据清空
      let res = await tiku.where({
        name: selectLib
      }).get()
      var len = res.data[0].title.length
      var answers = new Array(len);
      for (let i = 0; i < answers.length; i++) {
        var answerArr = new Array(4)
        answers[i] = answerArr
        for (let p = 0; p < answerArr.length; p++) {
          answers[i][p] = ""
        }
      }
      let updateRes = await wx.cloud.database().collection("userRecord").where({
        account: item.account,
        selectLib: app.globalData.selectLib,
      }).update({
        data: {
          index: 0,
          answers: answers
        }
      })
      if (updateRes.errMsg == "collection.update:ok") {
        wx.showToast({
          icon: "success",
          title: '清空成功',
        })
        return
      }
      console.log(updateRes.errMsg)
    }
  },

  onUnload() {},


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this
    var selectLib = app.globalData.selectLib
    //在这里获取顶部图片数据
    let cacheImage = wx.getStorageSync('image')
    that.setData({
      titleImage: cacheImage.touchCss[2],
      touch: cacheImage.touchCss[0],
      topSubject: selectLib,
    })
  },
  onShow: function () {
    this.setSpin()
  }
})